/*
 * rtc.c
 *
 *  Created on: 2017年9月20日
 *      Author: WEY
 */

#include "2440addr.h"
#include "serialcom.h"
#include "rtc.h"

#include "adc.h"
//RTCCON寄存器的bit0必须是1，才能对RTC时钟的寄存器进行写操作
//读取的时候，建议按照秒,分，小时，天，月，年的顺序进行读取

#define rRTCCON    (*(volatile unsigned char *)0x57000040)	//RTC control
#define rTICNT     (*(volatile unsigned char *)0x57000044)	//Tick time count
#define rRTCALM    (*(volatile unsigned char *)0x57000050)	//RTC alarm control
#define rALMSEC    (*(volatile unsigned char *)0x57000054)	//Alarm second
#define rALMMIN    (*(volatile unsigned char *)0x57000058)	//Alarm minute
#define rALMHOUR   (*(volatile unsigned char *)0x5700005c)	//Alarm Hour
#define rALMDATE   (*(volatile unsigned char *)0x57000060)	//Alarm date  // edited by junon
#define rALMMON    (*(volatile unsigned char *)0x57000064)	//Alarm month
#define rALMYEAR   (*(volatile unsigned char *)0x57000068)	//Alarm year
#define rRTCRST    (*(volatile unsigned char *)0x5700006c)	//RTC round reset
#define rBCDSEC    (*(volatile unsigned char *)0x57000070)	//BCD second
#define rBCDMIN    (*(volatile unsigned char *)0x57000074)	//BCD minute
#define rBCDHOUR   (*(volatile unsigned char *)0x57000078)	//BCD hour
#define rBCDDATE   (*(volatile unsigned char *)0x5700007c)	//BCD date  //edited
#define rBCDDAY    (*(volatile unsigned char *)0x57000080)	//BCD day   //edited by junon
#define rBCDMON    (*(volatile unsigned char *)0x57000084)	//BCD month
#define rBCDYEAR   (*(volatile unsigned char *)0x57000088)	//BCD year

#define CENTURYSTART 2000
#define UINT_8 unsigned char

static UINT_8 BIN2BCD2(int num)
{
	return (UINT_8)(((num%100)/10)<<4|(num%10));
}

void rtc_set(DateTime *pDateTime){
	rRTCCON |=1;
	rBCDYEAR=BIN2BCD2(pDateTime->year);
	rBCDMON=BIN2BCD2(pDateTime->month);
	rBCDDATE=BIN2BCD2(pDateTime->day);
	rBCDDAY=BIN2BCD2(pDateTime->weekday);
	rBCDHOUR=BIN2BCD2(pDateTime->hour);
	rBCDMIN=BIN2BCD2(pDateTime->min);
	rBCDSEC=BIN2BCD2(pDateTime->sec);
	rRTCCON &=~1;
}

void __irq rtc_isr(void){
	DateTime dateTime;
	rtc_get(&dateTime);
	adc_sample();
	ClearPending(1<<8);
}

void rtc_init(int isIntEnable)
{
	rRTCCON |=1;
	if(isIntEnable){
		rTICNT=0xff;
		pISR_TICK=(unsigned int)rtc_isr;
		rINTMSK &=~(1<<8);//开始RTC时钟中断
	}else{
		pISR_TICK=0;
		rINTMSK |=(1<<8);
	}
	rRTCCON &=~1;
	//允许写寄存器

}

void rtc_get(DateTime *pDateTime){
	unsigned char bcdData;
	bcdData=rBCDSEC;
	pDateTime->sec=(bcdData>>4)*10+(bcdData & 0xf);
	//分钟
	bcdData=rBCDMIN;
	pDateTime->min=(bcdData>>4)*10+(bcdData & 0xf);
	//小时
	bcdData=rBCDHOUR;
	pDateTime->hour=(bcdData>>4)*10+(bcdData & 0xf);
	//天
	bcdData=rBCDDATE;
	pDateTime->day=(bcdData>>4)*10+(bcdData & 0xf);
	//星期
	bcdData=rBCDDAY;
	pDateTime->weekday=(bcdData>>4)*10+(bcdData & 0xf);
	//月
	bcdData=rBCDMON;
	pDateTime->month=(bcdData>>4)*10+(bcdData &0xf);
	//年
	bcdData=rBCDYEAR;
	pDateTime->year=CENTURYSTART+(bcdData>>4)*10+(bcdData &0xf);
	rRTCCON &=~1;
}

